<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="选择卡券"
      width="1120px"
      top="10vh"
      append-to-body
      @close="close"
    >
      <!--      <el-tag>-->
      <!--        <i class="el-icon-warning"/>-->
      <!--        &nbsp;在此选择已经创建的券-->
      <!--      </el-tag>-->

      <div class="content">
        <!--筛选-->
        <div>
          <el-tabs v-model="filterForm.tableType" @tab-click="handleTab">
            <el-tab-pane label="券列表" name="coupon" />
            <el-tab-pane v-if="cardCouponType.length===0||cardCouponType.includes('times')||cardCouponType.includes('gift')" label="卡列表" name="card" />
          </el-tabs>
          <!--筛选-->
          <el-form ref="filterForm" :inline="true" :model="filterForm" label-width="60px" size="small">
            <el-form-item
              label="名称："
              prop="couponName"
            >
              <el-input
                v-model="filterForm.couponName"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item
              label="批次："
              prop="stockId"
            >
              <el-input
                v-model="filterForm.stockId"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item
              v-if="filterForm.tableType==='coupon'"
              label="类型："
              prop="couponTypes"
            >
              <el-select
                v-model="filterForm.couponTypes"
                filterable
                multiple
                collapse-tags
                placeholder="请选择"
                class="w-400"
                @change="(val)=>idsChange(val,'couponType')"
              >
                <el-option label="所有类型" value />
                <el-option
                  v-for="(v,k) in couponTypeUnLimitOptions"
                  :key="k"
                  :label="v"
                  :value="k"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="filterForm.tableType==='card'"
              label="类型："
              prop="cardTypes"
            >
              <el-select
                v-model="filterForm.cardTypes"
                filterable
                multiple
                collapse-tags
                placeholder="请选择"
                class="w-400"
                @change="(val)=>idsChange(val,'cardType')"
              >
                <el-option label="所有类型" value />
                <el-option
                  v-for="(v,k) in cardTypeUnLimitOptions"
                  :key="k"
                  :label="v"
                  :value="k"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" round @click="submitFilterForm">查 询</el-button>
              <el-button round @click="resetFilterForm">重 置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 列表 -->
        <div>
          <el-table
            v-loading="loading"
            :data="list"
            border
            stripe
            style="width: 100%"
            height="500"
            size="small"
            element-loading-text="加载中"
            empty-text="暂无数据"
          >
            <el-table-column prop="id" label="批次号" width="100" />
            <el-table-column prop="couponName" label="卡券名称">
              <template slot-scope="scope">
                <div v-if="filterForm.tableType==='coupon'">{{ scope.row.couponName }}</div>
                <div v-if="filterForm.tableType==='card'">{{ scope.row.cardName }}</div>
              </template>
            </el-table-column>
            <el-table-column label="卡券类型">
              <template slot-scope="scope">
                <div v-if="filterForm.tableType==='coupon'">{{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] }}</div>
                <div v-if="filterForm.tableType==='card'">{{ $store.getters.cardCouponTypeKeyOptions[scope.row.cardType] }}</div>
              </template>
            </el-table-column>
            <el-table-column label="卡券内容">
              <template slot-scope="scope">
                <div v-if="filterForm.tableType==='coupon'">
                  <div v-if="couponTypeGroup.cash.includes(scope.row.couponType)" class="cash">
                    {{ scope.row.denomination / 100 }}元
                  </div>
                  <div v-if="couponTypeGroup.discount.includes(scope.row.couponType)" class="discount">
                    {{ scope.row.discountPercent / 10 }}折
                  </div>
                  <div v-if="couponTypeGroup.exchange.includes(scope.row.couponType)" class="exchange">
                    {{ scope.row.exchangeThings }}
                  </div>
                </div>
                <div v-if="filterForm.tableType==='card'">
                  <div v-if="['times'].includes(scope.row.cardType)" class="cash">{{ scope.row.times }}次</div>
                  <div v-if="['gift'].includes(scope.row.cardType)" class="discount">{{
                    scope.row.denomination / 100
                  }}元
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="有效期">
              <template slot-scope="scope">
                {{ scope.row.startTime + ' ~ ' + scope.row.endTime }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-checkbox
                  v-model="checkedIds"
                  :disabled="originalCheckedIds.includes(scope.row.id)"
                  :label="scope.row.id"
                  @change="(val)=>checkboxChange(val,scope.row)"
                >
                  {{ checkedIds.includes(scope.row.id) ? '已选' : '选择' }}
                </el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total!==0"
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button :disabled="loading||checkedList.length===0" size="small" round type="primary" @click="submit">
          确定<span>（ 已选 {{ checkedList.length }}  ）</span></el-button>
        <el-button :disabled="loading" size="small" round @click="cancel">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { couponList } from '@/views/cardsAndOffer/api/coupon'
import { cardList } from '@/views/cardsAndOffer/api/card'

export default {
  props: {
    hasCheckedIds: {
      type: Array,
      default: () => {
        return []
      }
    },
    cardCouponType: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      cardCouponTypeOptions: {
        cash: '代金券',
        cash_wx_pay: '微信支付代金券',
        cash_wx_busi: '微信商家代金券',
        discount: '折扣券',
        discount_wx_busi: '微信商家折扣券',
        exchange: '兑换券',
        times: '次卡',
        gift: '礼品卡'
      },
      couponTypeOptions: {
        cash: '代金券',
        cash_wx_pay: '微信支付代金券',
        cash_wx_busi: '微信商家代金券',
        discount: '折扣券',
        discount_wx_busi: '微信商家折扣券',
        exchange: '兑换券'
      },
      couponTypeGroup: {
        cash: ['cash', 'cash_wx_pay', 'cash_wx_busi'],
        discount: ['discount', 'discount_wx_busi'],
        exchange: ['exchange']
      },
      cardTypeOptions: {
        times: '次卡',
        gift: '礼品卡'
      },
      couponTypeUnLimitOptions: {},
      cardTypeUnLimitOptions: {},
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: null,
      loading: false, // 表格loading
      // 数据
      originalCheckedIds: [],
      checkedIds: [],
      checkedList: [],
      lastCardTypesIds: [],
      lastCouponTypesIds: [],
      couponTypesIds: [''],
      cardTypesIds: [''],
      list: [], // 表格数据
      // 筛选数据
      filterForm: {
        tableType: 'coupon',
        status: 2,
        couponName: null,
        stockId: null,
        types: [],
        couponTypes: [],
        cardTypes: []
      }
    }
  },
  methods: {
    open() {
      console.log(this.hasCheckedIds)
      this.originalCheckedIds = this.hasCheckedIds
      this.checkedIds = this.hasCheckedIds
      this.getIds()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      Object.assign(this.$data, this.$options.data())
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 获取数据
     */
    getIds() {
      const typeArr = this.cardCouponType.length === 0 ? Object.keys(this.cardCouponTypeOptions) : this.cardCouponType
      typeArr.forEach(v => {
        if (Object.keys(this.couponTypeOptions).includes(v)) {
          this.couponTypeUnLimitOptions[v] = this.couponTypeOptions[v]
          this.couponTypesIds.push(v)
        }
        if (Object.keys(this.cardTypeOptions).includes(v)) {
          this.cardTypeUnLimitOptions[v] = this.cardTypeOptions[v]
          this.cardTypesIds.push(v)
        }
      })
      this.fetchData(1)
    },

    // 列表
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.loading = true
      const params = this.filterForm
      if (this.filterForm.tableType === 'coupon') {
        params.types = params.couponTypes.length === 0 ? this.couponTypesIds : params.couponTypes
        couponList(params)
          .then((res) => {
            this.list = res.data
          })
          .finally(() => {
            this.loading = false
          })
      }
      if (this.filterForm.tableType === 'card') {
        params.types = params.cardTypes.length === 0 ? this.cardTypesIds : params.cardTypes
        cardList(params)
          .then((res) => {
            this.list = res.data
          })
          .finally(() => {
            this.loading = false
          })
      }
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 查询
    submitFilterForm() {
      this.fetchData(1)
    },

    // 重置
    resetFilterForm() {
      this.$refs.filterForm.resetFields()
      this.fetchData(1)
    },

    /**
     * 按钮组
     */
    handleTab() {
      this.filterForm.couponName = null
      this.filterForm.stockId = null
      this.fetchData(1)
    },

    // 保存
    submit() {
      if (this.checkedList.length) this.resolve && this.resolve(this.checkedList)
      this.hide()
    },

    // 取消
    cancel() {
      this.hide()
    },

    /*
    * 状态栏
    * */
    checkboxChange(val, row) {
      if (val) {
        const params = {
          couponId: row.id,
          couponName: null,
          couponType: null,
          denomination: null,
          amount: 1,
          description: null
        }
        switch (this.filterForm.tableType) {
          case 'coupon':
            params.couponName = row.couponName
            params.couponType = row.couponType
            break
          case 'card':
            params.couponName = row.cardName
            params.couponType = row.cardType
            break
        }
        switch (params.couponType) {
          case 'cash':
          case 'cash_wx_pay':
          case 'cash_wx_busi':
            params.denomination = row.denomination
            break
          case 'discount':
          case 'discount_wx_busi':
            params.denomination = row.discountPercent
            break
          // case 'exchange':
          //   params.denomination = row.exchangeThings
          //   break
          case 'times':
            params.denomination = row.times
            break
          case 'gift':
            params.denomination = row.denomination
            break
        }
        this.checkedList.push(params)
      } else {
        this.checkedList.splice(this.checkedList.findIndex(item => item.id === row.id), 1)
      }
    },

    // 多选改变
    idsChange(val, type) {
      let lastIdsType = ''
      let idsType = ''
      let allIds = ''
      switch (type) {
        case 'couponType':
          lastIdsType = 'lastCouponTypesIds'
          idsType = 'couponTypes'
          allIds = 'couponTypesIds'
          break
        case 'cardType':
          lastIdsType = 'lastCardTypesIds'
          idsType = 'cardTypes'
          allIds = 'cardTypesIds'
          break
      }
      const lastVal = this[lastIdsType]
      if (val.includes('')) {
        this.filterForm[idsType] = this[allIds]
      }
      if (lastVal.includes('') && !val.includes('')) {
        this.filterForm[idsType] = []
      }
      if (lastVal.includes('') && val.includes('')) {
        val.splice(
          val.findIndex((v) => v === ''),
          1
        )
        this.filterForm[idsType] = val
      }
      if (!lastVal.includes('') && !val.includes('')) {
        if (val.length === this[allIds].length - 1) {
          this.filterForm[idsType] = [''].concat(val)
        }
      }
      this[lastIdsType] = this.filterForm[idsType]
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.content {
  ::v-deep {
    .el-tabs__header {
      margin-bottom: 10px;
      background-color: #fff;
      border-radius: 0 0 5px 5px;
    }

    .el-tabs__nav-wrap::after {
    }

    .el-tabs__active-bar {
      height: 4px;
    }
  }
}
</style>
